package com.tanhua.server.service;

import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.User;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
public class PhoneService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private UserApi userApi;

    public void sendMsg(String phone) {
        String code="123456";//为了测试方便，将验证码固定
        redisTemplate.opsForValue().set(phone,code, Duration.ofMinutes(5));//将验证码存入Redis
    }

    public boolean checkVerificationCode(String code) {
        String redisCode = redisTemplate.opsForValue().get(UserHolder.getMobile());
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)){
            return false;
        }
        //删除redis中的验证码
        redisTemplate.delete(UserHolder.getMobile());
        return true;
    }

    public void update(String phone) {
        User user = userApi.findByMobile(phone);
        if (user == null){//新号码，进行保存
            user=new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            user.setId(UserHolder.getUserId());
            userApi.update(user);
        }else {//号码已存在
            throw new BusinessException(ErrorResult.mobileError());
        }
    }
}
